<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.query.name" class="filter-item" placeholder="Agent 名称" style="width: 200px;" @keyup.enter.native="filter" />
      <el-button class="filter-item" icon="el-icon-search" style="margin-left: 10px;" type="primary" @click="filter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column prop="id" align="center" label="id" width="95px" sortable>
        <template v-slot="{row}">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Agent 名称" prop="name" sortable width="280px">
        <template v-slot="{row}">
          {{ row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="版本" prop="version" width="70px">
        <template v-slot="{row}">
          {{ row.version }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="运行系统" prop="systemType" width="100px">
        <template v-slot="{row}">
          {{ row.systemType }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center" width="80px">
        <template v-slot="{row}">
          <el-tag v-if="row.status === 1" type="info">离线</el-tag>
          <el-tag v-else type="success">在线</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="Agent Key" prop="AgentKey" width="180px">
        <template v-slot="{row}">
          <el-button plain size="small" @click="copyToClipboard(row.key)">点击复制</el-button>
        </template>
      </el-table-column>
      <el-table-column label="mockBaseURL" prop="mockBaseUrl">
        <template v-slot="{row}">
          {{ row.mockBaseUrl }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200px">
        <template v-slot="{row}">
          <el-button type="primary" size="small" @click="handleUpdate(row)">修改</el-button>
          <el-button :disabled="row.status !== 2" size="small" @click="handleReboot(row)">重启 Agent</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="listQuery.totalRecords>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.pageNum" :total="listQuery.totalRecords" @pagination="fetchData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="550px" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="left" label-width="100px">
        <el-form-item label="Agent 名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入 Agent 名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?create():update()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, create, update, reboot } from '@/api/functional_test/agent'
import Pagination from '@/components/Pagination'

export default {
  components: { Pagination },
  data() {
    return {
      list: null,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        totalRecords: 0,
        orders: undefined,
        query: {}
      },
      form: {
        id: undefined,
        name: ''
      },
      dialogFormVisible: false,
      formLabelWidth: '120px',
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      rules: {
        name: [
          { required: true, message: '请输入 Agent 名称', trigger: 'change' },
          { max: 50, message: 'Agent 名称长度不能超过 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data.list
        this.listQuery.totalRecords = response.data.page.totalRecords
        this.listLoading = false
      })
    },
    filter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    },
    // 创建
    create() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.form).then(() => {
            this.dialogFormVisible = false
            this.$message({ message: '添加成功!', type: 'success' })
            this.fetchData()
          })
        }
      })
    },
    // 修改
    update() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          update(this.form).then(() => {
            const index = this.list.findIndex(v => v.id === this.form.id)
            this.fetchData()
            this.list.splice(index, 1, this.form)
            this.dialogFormVisible = false
            this.$message({ message: '修改成功!', type: 'success' })
          })
        }
      })
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: ''
      }
    },
    // 点击添加按钮
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 点击修改按钮
    handleUpdate(row) {
      this.form = Object.assign({}, row) // 复制行数据
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 重启 agent
    handleReboot(row) {
      this.$confirm('是否重启该 Agent：' + row.name + ' ?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        reboot(row.key).then(() => {
          this.$message({ message: '重启成功!', type: 'success' })
        })
      })
    },
    // 复制 Agnet Key
    async copyToClipboard(key) {
      try {
        await navigator.clipboard.writeText(key) // 将 key 复制到剪切板中
        this.$message({ message: '复制成功', type: 'success' })
      } catch (err) {
        this.$message({ message: '复制失败', type: 'error' })
      }
    }
  }
}
</script>
